import shutil

import cv2
import os

def preprocess_image(filename):
    # 读取图像
    image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)

    if image is None:
        print(f"Error: Image at path '{filename}' could not be read.")
        return None

    # 高斯滤波，可以减少图像噪声
    blur = cv2.GaussianBlur(image, (3, 3), 0)

    # 直方图均衡化，改善图像对比度
    image_eq = cv2.equalizeHist(blur)

    # # 显示原始图像和处理后的图像
    # cv2.imshow('Original Image', image)
    # cv2.imshow('Gaussian Blurred Image', blur)
    # cv2.imshow('Histogram Equalized Image', image_eq)
    #
    # # 等待按键，然后关闭所有窗口
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    return image_eq


unprocessed_folder = 'imgs/origin'
source_folder = 'imgs'

if not os.path.exists(unprocessed_folder):
    os.makedirs(unprocessed_folder)

# 使用函数，传入图像路径
for filename in os.listdir(source_folder):
    if filename.endswith(('.jpg', '.jpeg', '.png')):
        file_path = os.path.join(source_folder, filename)
        target_file_path = os.path.join(unprocessed_folder, filename)
        shutil.copy(file_path, target_file_path)

        processed_image = preprocess_image(file_path)
        cv2.imwrite(file_path, processed_image)
